package com.heima.admin.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.service.AdUserService;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.model.admin.dtos.AdLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdLoginVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
* @author 马毅爽
* @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
* @createDate 2023-12-17 14:50:57
*/
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
    implements AdUserService{

    @Override
    public ResponseResult login(AdLoginDto dto) {
        // 1. 检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 查询用户
        AdUser user = lambdaQuery().eq(AdUser::getName, dto.getName()).one();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 校验密码
        String salt = user.getSalt();
        String password = dto.getPassword();
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (password.equals(user.getPassword())){
            // 4. 返回数据
            String token = AppJwtUtil.getToken(user.getId().longValue());
            user.setPassword("");
            user.setSalt("");
            AdLoginVo adLoginVo = AdLoginVo.builder().user(user).token(token).build();
            return ResponseResult.okResult(adLoginVo);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}




